package com.sdms.core.login;

import com.sdms.core.user.SystemUser;
import com.sdms.core.util.PasswordEncryptionUtil;

/**
 * Secure Delivery Management System (SDMS)
 * com.sdms.core.login
 * User: Tharindu Munasinghe
 * Mar 7, 2013 3:40:39 PM
 * Copyright � 2013
 */
public class LoginService implements ILoginService
{
	private IUserStore userStore;
	
	public LoginService() {
		this.userStore = UserStore.getInstance();
	}
	
	@Override
	public String login( String userName, String passWord ) throws IllegalAccessException
	{
		SystemUser user = userStore.viewUser( userName );
		if ( user == null )
		{
			throw new IllegalAccessException();
		}
		else if ( !PasswordEncryptionUtil.validatePassword( passWord, user.getPassWord() ) )
		{
			throw new IllegalAccessException();
		}
		else
		{
			UserSession userSession = createNewUserSession( user );
			SessionStore.addNewSession( userSession );
			return userSession.getSesionId();
		}
	}

	@Override
	public void logOut(String sessionId) {
		SessionStore.removeSession(sessionId);
	}	
	
	private UserSession createNewUserSession(SystemUser user) {
		UserSession ses = new UserSession();
		ses.setUserName(user.getUserName());
		ses.setRole(user.getRole());
		return ses;		
	}
}
